"""
订单模型
"""
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

from app import db


class Order(db.Model):
    """订单模型"""
    __tablename__ = 'orders'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    order_number = db.Column(db.String(50), unique=True, nullable=False)
    total_amount = db.Column(db.Float, nullable=False)
    status = db.Column(db.String(20), default='pending')  # pending, confirmed, shipped, delivered, cancelled
    payment_status = db.Column(db.String(20), default='pending')  # pending, paid, failed, refunded
    shipping_address = db.Column(db.Text)
    billing_address = db.Column(db.Text)
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    items = db.relationship('OrderItem', backref='order', lazy=True, cascade='all, delete-orphan')
    
    def __init__(self, user_id, order_number, total_amount, shipping_address=None, 
                 billing_address=None, notes=None):
        self.user_id = user_id
        self.order_number = order_number
        self.total_amount = total_amount
        self.shipping_address = shipping_address
        self.billing_address = billing_address
        self.notes = notes
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'order_number': self.order_number,
            'total_amount': self.total_amount,
            'status': self.status,
            'payment_status': self.payment_status,
            'shipping_address': self.shipping_address,
            'billing_address': self.billing_address,
            'notes': self.notes,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'items': [item.to_dict() for item in self.items]
        }
    
    def __repr__(self):
        return f'<Order {self.order_number}>'
    
    def update_status(self, new_status):
        """更新订单状态"""
        valid_statuses = ['pending', 'confirmed', 'shipped', 'delivered', 'cancelled']
        if new_status in valid_statuses:
            self.status = new_status
            return True
        return False
    
    def update_payment_status(self, new_status):
        """更新支付状态"""
        valid_statuses = ['pending', 'paid', 'failed', 'refunded']
        if new_status in valid_statuses:
            self.payment_status = new_status
            return True
        return False
    
    def calculate_total(self):
        """计算订单总金额"""
        total = 0.0
        for item in self.items:
            total += item.quantity * item.unit_price
        self.total_amount = total
        return total
    
    @classmethod
    def find_by_order_number(cls, order_number):
        """根据订单号查找订单"""
        return cls.query.filter_by(order_number=order_number).first()
    
    @classmethod
    def find_by_user_id(cls, user_id):
        """根据用户ID查找订单"""
        return cls.query.filter_by(user_id=user_id).order_by(cls.created_at.desc()).all()
    
    @classmethod
    def find_by_status(cls, status):
        """根据状态查找订单"""
        return cls.query.filter_by(status=status).all()
    
    @classmethod
    def generate_order_number(cls):
        """生成订单号"""
        import uuid
        return f"ORD-{uuid.uuid4().hex[:8].upper()}"


class OrderItem(db.Model):
    """订单项模型"""
    __tablename__ = 'order_items'
    
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('orders.id'), nullable=False)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)
    quantity = db.Column(db.Integer, nullable=False)
    unit_price = db.Column(db.Float, nullable=False)
    
    def __init__(self, order_id, product_id, quantity, unit_price):
        self.order_id = order_id
        self.product_id = product_id
        self.quantity = quantity
        self.unit_price = unit_price
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'order_id': self.order_id,
            'product_id': self.product_id,
            'quantity': self.quantity,
            'unit_price': self.unit_price,
            'total_price': self.quantity * self.unit_price
        }
    
    def __repr__(self):
        return f'<OrderItem {self.id}>'
    
    @classmethod
    def find_by_order_id(cls, order_id):
        """根据订单ID查找订单项"""
        return cls.query.filter_by(order_id=order_id).all()